<template>
  <BasicContainer>
    <FyCurd
      ref="crud"
      v-model="form"
      :page.sync="page"
      :data="tableData"
      :permission="permissionList"
      :table-loading="tableLoading"
      :option="tableOption"
      :before-open="handleOpenBefore"
      @selection-change="selectionChange"
      @on-load="getList"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @size-change="sizeChange"
      @current-change="currentChange"
      @row-update="handleUpdate"
      @row-save="handleSave"
      @row-del="handleDel">
      <template #menu="{ row }">
        <ElButton
          v-if="permissions.problem_rectify_add"
          type="text"
          icon="el-icon-edit"
          size="small"
          @click="addFeedBack(row)">
          整改反馈
        </ElButton>
      </template>
      <template #menuLeft>
        <ElButton
          v-if="permissions.problem_rectify_export"
          class="filter-item"
          plain
          type="primary"
          size="small"
          icon="el-icon-download"
          @click="exportExcel">
          导出
        </ElButton>
        <ElButton
          v-if="permissions.problem_rectify_export"
          class="filter-item"
          plain
          type="primary"
          size="small"
          icon="el-icon-upload"
          @click="$refs.excelUpload.show()">
          导入
        </ElButton>
        <ElButton
          v-if="permissions.problem_rectify_add"
          type="primary"
          size="small"
          icon="el-icon-edit"
          @click="timingReming()">
          定时提醒
        </ElButton>
      </template>
      <template #problemInforNum="{ row }">
        <ElTag style="cursor: pointer" @click="problemInforNumClick(row)">{{ row.problemInforNum }}</ElTag>
      </template>
      <template #problemInforNumForm>
        <ElInput v-model="form.problemInforNum" :disabled="proInforNumDisplay" placeholder="选择问题单号" />
        <div>
          <ElTag v-show="showType !== 'view'" style="cursor: pointer" @click="openProblemInfoDialog()">
            选择问题列表
          </ElTag>
          <ElTag v-show="form.problemInforNum" style="cursor: pointer" @click="showProblemInforDialog()">
            查看问题单
          </ElTag>
        </div>
      </template>
      <template #thoseResponsibleForm="{ disabled }">
        <ElInput
          v-model="form.thoseResponsible"
          :disabled="disabled"
          placeholder="选择责任人"
          @focus="openSelectUserDialog" />
      </template>
      <template #functionalNameForm="{ disabled }">
        <VueTreeSelect
          v-model="form.functionalOuid"
          :options="functionDeptOption"
          :normalizer="normalizer"
          :disabled="disabled"
          :show-count="true"
          placeholder="选择职能部门"
          @select="functionNameSelect" />
      </template>
      <template #timelimitTypeForm="{ disabled }">
        <ElSelect
          v-model="form.timelimitType"
          :disabled="disabled"
          placeholder="请选择完成时限"
          @change="timelimitTypeChange()">
          <ElOption key="0" label="长期" value="0" />
          <ElOption key="1" label="限期" value="1" />
          <ElOption key="2" label="立行立改" value="2" />
        </ElSelect>
      </template>
      <!--      <template #thoseResponsibleForm="{ type }">
        <RectifyDetailTable
          ref="rectifyDetailTable"
          :concurent-type="type"
          :rectify-id="form.id"
          :rectify-num="form.number"/>
      </template>-->
      <template #thoseResponsible="scope">
        <ElTag v-for="item in scope.row.thoseResponsible ? scope.row.thoseResponsible.split(',') : ''" :key="item">
          {{ item }}
        </ElTag>
      </template>
      <template #responsibilityDept="scope">
        <ElTag v-for="item in scope.row.responsibilityDept ? scope.row.responsibilityDept.split(',') : ''" :key="item">
          {{ item }}
        </ElTag>
      </template>
      <!-- 附件上传组件{ 需要传入uniqueCode/model/classify} -->
      <template #uploadPageForm>
        <UploadPage
          ref="UploadPage"
          :unique-code="uniqueCode"
          :upload-permissions="permissionList"
          :view-type="showType"
          model="problem"
          classify="rectify" />
      </template>
    </FyCurd>
    <ElementDialog :visible.sync="visibleFeedback" title="整改反馈" top="5%" width="95%">
      <FeedBackModel v-if="visibleFeedback" ref="feedBack" :rectify-id="rectifyId" :rectify-num="rectifyNum" />
      <template #footer>
        <span class="dialog-footer">
          <ElButton @click="visibleFeedback = false">关闭</ElButton>
        </span>
      </template>
    </ElementDialog>
    <!--excel 模板导入 -->
    <ExcelUpload
      ref="excelUpload"
      title="整改措施信息导入"
      :url="`${services.personnelService}/rectify/import`"
      :temp-url="`${services.personnelService}/sys-file/local/rectify.xlsx`"
      temp-name="整改措施信息导入模板.xlsx"
      @refreshDataList="refreshChange" />
    <ProblemInfo v-if="visibleProblemInfo" ref="proInfo" @getProblemInfoData="getProblemInfoData" />
    <UserPicker
      v-if="visibleSelectUser"
      :pre-selected-users="users"
      :reserve-position-on-close="false"
      close-on-click-modal
      :visible.sync="visibleSelectUser"
      multiple
      @confirm="getUserData" />

    <DlgMessageUserObjectForm
      ref="message"
      :visible.sync="showMessage"
      doc-code="Recitify"
      :form-disabled="false"
      source-type="ProblemRectify" />
    <InforModel v-show="inforVisible" ref="infor" />
  </BasicContainer>
</template>

<script>
  import {
    putObj,
    delObj,
    getRegularlyRemind,
    getInforName,
    addAndRectifyDetailed,
    fetchThoseResponsibleList
  } from '@/api/problem/rectify'
  import { addRectifyDetaileds, getRectifyDetailedList, delRectifyDetailed } from '@/api/problem/rectifydetailed'
  import { getNumber } from '@/api/problem/infor'
  import { fetchTree } from '@/api/admin/dept'
  import { tableOption } from '@/const/crud/problem/rectify'
  import { mapState } from 'vuex'
  import FeedBackModel from '@/module/problem/feedback/FeedBackModel'
  import InforModel from '@/module/problem/infor/InforModel'
  import { services } from '@/config'
  import { uuid } from '@web-utils/integrations/uuid'

  export default {
    name: 'Rectify',
    components: {
      FeedBackModel,
      InforModel
    },
    props: {
      problemInforId: {
        type: Number,
        default: -1
      },
      problemInforNum: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        inforVisible: false,
        tableOption,
        form: {
          functionalOuid: null,
          functionalName: null
        },
        visibleProblemInfo: false,
        proInforNumDisplay: false,
        functionDeptOption: [],
        visibleResponsiPeople: false,
        visibleFeedback: false,
        rectifyId: -1,
        rectifyNum: '',
        dutyDeptData: [],
        users: [],
        visibleSelectUser: false,
        selectData: [],
        showMessage: false,
        sourceId: '',
        showType: '',
        uniqueCode: '',
        services
      }
    },
    // eslint-disable-next-line vue/order-in-components
    computed: {
      ...mapState('user', ['permissions']),
      permissionList() {
        return {
          addBtn: this.$isEmpty(this.permissions.problem_rectify_add, false),
          delBtn: this.$isEmpty(this.permissions.problem_rectify_del, false),
          editBtn: this.$isEmpty(this.permissions.problem_rectify_edit, false),
          downloadBtn: this.$isEmpty(this.permissions.problem_rectify_download, false)
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        this.getdeptTreeSelect()
      },
      // 列表查询
      getList(page, params) {
        if (this.problemInforId > 0) {
          this.searchForm.problemInforId = this.problemInforId
        }
        this.tableLoading = true
        fetchThoseResponsibleList(
          Object.assign(
            {
              current: page.currentPage,
              size: page.pageSize,
              descs: 'create_time'
            },
            params,
            this.searchForm
          )
        )
          .then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          })
          .catch(() => {
            this.tableLoading = false
          })
      },
      // 删除
      handleDel: function (row, index) {
        this.$confirm(`是否确认删除ID为${row.id}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return delObj(row.id)
          })
          .then(data => {
            this.$message.success('删除成功')
            this.getList(this.page)
          })
      },
      // 更新
      handleUpdate: function (row, index, done, loading) {
        putObj(row)
          .then(data => {
            this.$message.success('修改成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 保存
      handleSave: function (row, done, loading) {
        this.$nextTick(() => {
          row.rectifyDetaileds = this.$refs.rectifyDetailTable.saveData
        })
        addAndRectifyDetailed(row)
          .then(data => {
            this.$message.success('添加成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 打开模态框之前
      handleOpenBefore(show, type) {
        window.boxType = type
        this.showType = type
        if (this.problemInforId !== -1 && this.problemInforNum !== '') {
          this.form.problemInforId = this.problemInforId
          this.form.problemInforNum = this.problemInforNum
          this.proInforNumDisplay = true
        }
        // console.log(type)
        // 添加附件参数
        if (type === 'add') {
          this.form.functionalOuid = 254
          const tempUuid = uuid(true)
          this.uniqueCode = tempUuid
          this.form.unid = tempUuid
        } else {
          this.uniqueCode = this.form.unid
        }
        show()
      },
      // 每页条数改变事件
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 当前页发生改变事件
      currentChange(current) {
        this.page.currentPage = current
      },
      // 查询事件
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新事件
      refreshChange() {
        this.getList(this.page)
      },
      //  导出excel
      exportExcel() {
        const exportFileName = `整改措施_${this.$dateFormat(new Date())}.xlsx`
        this.$downBlobFile(`${services.personnelService}rectify/export`, this.searchForm, exportFileName)
      },
      // 打开问题信息模态框
      openProblemInfoDialog() {
        this.visibleProblemInfo = true
        this.$nextTick(() => {
          this.$refs.proInfo.init()
        })
      },
      // 获取选中问题信息数据
      getProblemInfoData(listInfo) {
        if (listInfo.length > 0) {
          this.form.problemInforNum = listInfo[0].number
          this.form.problemInforId = listInfo[0].id
        }
        // console.log(listInfo[0])
      },
      /** 查询菜单下拉树结构 */
      getdeptTreeSelect() {
        fetchTree().then(response => {
          this.functionDeptOption = response.data.data
        })
      },
      // 获取部门信息
      getDeptData(listDept) {
        if (listDept.length > 0) {
          this.form.functionalName = listDept[0].name
          this.form.functionalOuid = listDept[0].id
          this.form.functionalFullname = listDept[0].fullname
        }
      },
      timelimitTypeChange() {
        if (this.form.timelimitType === '0' || this.form.timelimitType === '2') {
          this.tableOption.column[11].display = false
          this.tableOption.column[12].display = false
        } else if (this.form.timelimitType === '1') {
          this.tableOption.column[11].display = true
          this.tableOption.column[12].display = true
        }
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      /** 添加责任人 */
      addResponsiPepople(row) {
        this.rectifyId = parseInt(row.id)
        this.rectifyNum = row.number
        this.visibleResponsiPeople = true
        this.dutyDeptData = []
        const query = { rectifyId: row.id }
        getRectifyDetailedList(query).then(response => {
          this.dutyDeptData = response.data.data
        })
      },
      issuedTask(row) {},
      // 定时通知
      timingReming() {
        if (this.selectData.length === 0) {
          this.$message.warning('清先选择需要提示的整改单号')
          return
        }
        if (this.selectData.length > 1) {
          this.$message.warning('选择一条整改反馈')
          return
        }
        this.showMessage = true
        // 获取整改措施责任人
        getRegularlyRemind(this.selectData[0].id).then(res => {
          const rows = res.data.data
          if (rows.length > 0) {
            getInforName(this.selectData[0].id).then(res => {
              this.$refs.message.dataForm.subject = res.data.msg
            })
            this.sourceId = this.selectData[0].id
            // this.$refs.message.form.sourceId = this.selectData[0].id
            this.$refs.message.dataForm.timelimitType = this.selectData[0].timelimitType
            this.$refs.message.dataForm.startdate = this.selectData[0].startdate
            this.$refs.message.dataForm.enddate = this.selectData[0].enddate
            // console.log(this.$refs.message.dataForm)
            this.$refs.message.rows = rows
            this.$refs.message.init(this.sourceId)
          }
        })
      },
      addFeedBack(row) {
        this.rectifyId = parseInt(row.id)
        this.rectifyNum = row.number
        this.visibleFeedback = true
      },
      deleteDutyname(index, row) {
        if (row.id !== undefined) {
          delRectifyDetailed(row.id)
        }
        this.dutyDeptData.splice(index, 1)
      },
      // 获取选择的用户信息
      getUserData(userData) {
        this.form.thoseResponsibleIds = userData.map(item => item.id)
        this.form.thoseResponsible = userData.map(item => item.name)
      },
      // 打开选择用户选择框
      openSelectUserDialog() {
        this.visibleSelectUser = true
      },
      // 保存责任人
      saveDudyDept() {
        if (this.dutyDeptData.length > 0) {
          for (let i = 0; i < this.dutyDeptData.length; i++) {
            this.dutyDeptData[i].rectifyId = this.rectifyId
            this.dutyDeptData[i].rectifyNum = this.rectifyNum
          }
          addRectifyDetaileds(this.dutyDeptData)
            .then(data => {
              this.$message.success('添加成功')
              this.getList(this.page)
            })
            .catch(() => {})
        }
      },
      selectionChange(list) {
        this.selectData = list
      },
      functionNameSelect(node, instanceId) {
        this.form.functionalOuid = node.id
        this.form.functionalName = node.name
      },
      showProblemInforDialog() {
        // this.inforVisible = true
        getNumber(this.form.problemInforNum).then(response => {
          this.$refs.infor.$refs.crud.rowView(response.data.data)
        })
      },
      problemInforNumClick(row) {
        this.showType = 'view'
        const _this = this
        getNumber(row.problemInforNum).then(response => {
          _this.$refs.infor.$refs.crud.rowView(response.data.data)
        })
      }
    }
  }
</script>
